<template>
<!-- 组件最外层 -->
    <div class="login-bg">
    <!--   用于居中   -->
      <el-row type="flex" justify="center" align="middle" style="height: 100vh">
      <!--    注册表单    -->
        <el-card class="product-card" style="min-width: 480px;min-height: 300px;margin-bottom: 0" shadow="always">
          <div class="product-title">校园二手交易平台</div>
          <el-form ref="Form" style="max-width: 600px" :model="form" :rules="rules" label-width="auto">
            <!--     用户名       -->
            <el-form-item label="昵称" prop="username">
              <el-input
                  prefix-icon="el-icon-user"
                  v-model="form.username"
                  style="width: 100%"
                  placeholder="请输入昵称"
              />
            </el-form-item>
            <!--     邮箱       -->
            <el-form-item label="邮箱" prop="email">
              <el-input
                  prefix-icon="el-icon-message"
                  v-model="form.email"
                  style="width: 100%"
                  placeholder="请输入邮箱"
              />
            </el-form-item>
            <!--     头像       -->
            <el-form-item label="头像" prop="imageUrl">
              <el-upload
                  class="img-uploader"
                  :action="avatarUploadUrl"
                  :show-file-list="false"
                  :on-success="uploadSuccess"
                  :before-upload="beforeUpload"
                  :headers="uploadHeaders"
                  accept="image/*">
                <img v-if="form.avatar" :src="form.avatar" class="upload-img" alt="上传的图片">
                <i v-else class="el-icon-plus img-uploader-icon"> 文件大小限制 {{ sizeMax }} MB</i>
              </el-upload>
            </el-form-item>
            <!--     密码输入框       -->
            <el-form-item label="密码" prop="password">
              <el-input
                  prefix-icon="el-icon-key"
                  v-model="form.password"
                  style="width: 100%"
                  placeholder="请输入密码"
                  type="password"
                  show-password
              />
            </el-form-item>
            <!--     手机号       -->
            <el-form-item label="手机" prop="phone">
              <el-input
                  prefix-icon="el-icon-phone"
                  v-model="form.phone"
                  style="width: 100%"
                  placeholder="请输入手机号"
              />
            </el-form-item>
            <!--     验证码       -->
            <el-form-item label="验证码" prop="code">
              <div class="valid-code">
                <el-input
                    prefix-icon="el-icon-lock"
                    v-model="form.code"
                    style="width: 100%"
                    placeholder="请输入验证码"
                />
                <el-button type="primary" @click="onSend" :disabled="isCounting" >{{buttonText}}</el-button>
              </div>
            </el-form-item>
            <!--     注册按钮       -->
            <div style="display: flex;align-items: center;justify-content: center">
              <el-form-item class="no-margin" label-width="0" style="margin-bottom: 0">
                <el-tooltip content="请先获取验证码" effect="light">
                  <el-button type="primary" @click="onRegister" :disabled="!emailSend">注册</el-button>
                </el-tooltip>
              </el-form-item>
            </div>
            <!--     登录链接       -->
            <div style="display: flex;align-items: center;justify-content: right">
              <el-form-item label-width="0" style="margin-bottom: 0">
                <span>已有账号？
                  <el-link type="primary" @click="$router.push('/login')">去登录</el-link>
                </span>
              </el-form-item>
            </div>
          </el-form>
        </el-card>
      </el-row>
    </div>
</template>

<script>
// 后端接口函数导入
import {apiRegister, apiSendCode} from "@/api/api";

export default {
  data(){
    return {
      sizeMax : 5,
      avatarUploadUrl: "/api/file/upload", // 上传头像的接口路径
      uploadHeaders : { // 加JWT认证
        token: localStorage.getItem("token")
      },
      emailSend: false, // 用于注册按钮的 disable
      isCounting: false, // 用于验证码的倒数
      countdown: 60,
      buttonText: "获取验证码",
      // 注册表单的数据
      form: {
        username: "", // 昵称
        password: "",
        email: "",
        phone: "",
        avatar : "", // 头像地址
        code: "", // 验证码
        gender: "" // 性别
      },
      // 表单验证规则
      rules: {
        email: [
          { required: true, message: '请输入用户名（邮箱）', trigger: 'blur' },
          { pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '邮箱格式错误', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'change' },
          { min: 6, message: '密码长度应大于等于 6', trigger: 'change' },
        ],
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {pattern: /^[0-9]{11}$/, message: "手机号格式错误", trigger: 'blur'}
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          {min:6, max:6, message: "格式错误", trigger: 'blur'}
        ]
      },
    }
  },
  methods :{
    // 头像上传成功后处理
    uploadSuccess(res){
      // 1. 验证后端数据正常
      if (res.code !== 200){
        this.$message.error(`图片上传失败 ${res.message}`);
      }
      // 2. 获取后端Url
      let url = res.data;
      // 3. 添加前端代理检测api
      if (url && !/^https?:\/\//.test(url)){
        url = url.startsWith('/api') ? url : ("/api" + url);
      }
      // 4. 表单数据赋值
      this.form.avatar = url;
      this.$message.success("图片上传成功");
    },
    // 上传前
    beforeUpload(file){
      // 1. 文件类型和大小验证
      const isImg = file.type.startsWith("image/");
      const isLt5M = file.size / 1024 / 1024 < this.sizeMax; // 大小限制 5 MB
      if (!isImg){
        this.$message.error("必须是图片类型");
        return false
      }
      if (!isLt5M){
        this.$message.error(`图片大小限制 ${this.sizeMax} MB`);
        return false
      }
      return true;
    },
    // 验证码发送
    onSend(){
      // 1. 调用API
      apiSendCode(this.form).then(res => {
        // 2. 检测后端数据是否正常
        if (res?.code === 200){
          this.$message.success("发送成功！");
          this.emailSend = true;
          if (this.isCounting) return;
          // 3. 设置倒计时
          this.isCounting = true;
          this.buttonText = `${this.countdown}s后重新获取`;
          const timer = setInterval(() => {
            this.countdown--;
            this.buttonText = `${this.countdown}s后重新获取`;
            // 4. 按钮恢复正常
            if (this.countdown <= 0) {
              clearInterval(timer);
              this.isCounting = false;
              this.countdown = 60;
              this.buttonText = "获取验证码";
            }
          }, 1000);
        }else{
          this.$message.error(res.message);
          this.emailSend = false
        }
      })
    },
    // 注册按钮
    onRegister(){
      // 1. 验证表单
      this.$refs.Form.validate(valid=> {
        if (valid){
          // 2. 验证通过，调用API
          apiRegister(this.form).then(res => {
            if (res?.code === 200){
              this.$message.success("注册成功！");
              this.$router.push("/login");
            }else{
              this.$message.error(res.message);
            }
          })
        }else{
          this.$message.error("请正确填写表单")
        }
      })
    }
  }
}
</script>

<style scoped lang="less">
.upload-img {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
  border: 1px solid #eee;
}
.img-uploader-icon{
  color: gray; border: 2px dashed #bbbbbb;padding: 1rem;border-radius: 4px;
}

.login-bg{
  height: 100%;
  background-size: cover;
  background: url("@/assets/bg/bg.png") center;
}

.product-card{
  border-radius: 16px;
  padding: 32px 24px 0;
  box-shadow: 2px 4px 10px rgba(64, 158, 255, 0.5) !important
}
// 标题样式
.product-title{
  text-align: center;
  font-size: 2rem;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 24px;
  text-shadow: 1px 2px 5px rgba(0, 0, 139, 0.4);
}
// 用于一行的输入框和按钮同行显示
.valid-code{
  display: flex;
  gap: 1rem;
}
</style>